/**
 * @author: cll
 * @version:1.0
 * @date: 2021-08-12 17:20
 * @descripton:
 */
package com.fshows.leshuapay.sdk.util.risksign;

import com.fshows.leshuapay.sdk.exception.LeshuaException;
import com.fshows.leshuapay.sdk.request.LeshuaBizRequest;
import com.fshows.leshuapay.sdk.request.merchant.riskmanagement.RiskCommitRequest;
import com.fshows.leshuapay.sdk.util.SignUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * @author cll
 * @version RiskCommitSign.java, v 0.1 2021-08-12 17:20 cll 申诉资料提交签名
 */
@Slf4j
public class RiskCommitSign implements LeshuaRiskSign {

    @Override
    public LeshuaBizRequest doSign(Serializable request, String privateKey, String agentId)
            throws LeshuaException {
        // 签名规则 key= merchantId&ticketNumber&appealMaterial&agentKey;
        try {
            RiskCommitRequest riskCommitRequest = null;
            if (request instanceof RiskCommitRequest) {
                riskCommitRequest = (RiskCommitRequest) request;
                StringBuffer key = getStringBuffer(privateKey, riskCommitRequest);
                riskCommitRequest.setSign(SignUtil.doSign(key.toString()));
            }
            return riskCommitRequest;
        } catch (Exception e) {
            log.error("RiskCommitSign->> doSign 签名异常,ex={}", e);
            throw new LeshuaException("风控签名异常", e);
        }
    }

    private StringBuffer getStringBuffer(String privateKey, RiskCommitRequest riskCommitRequest) {
        StringBuffer key = new StringBuffer(riskCommitRequest.getMerchantId());
        key.append("&");
        key.append(riskCommitRequest.getTicketNumber());
        key.append("&");
        key.append(riskCommitRequest.getAppealMaterial());
        key.append("&");
        key.append(privateKey);
        return key;
    }
}
